package com.xieli.invitesdk

import android.util.Log
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.xieli.invitesdk.utils.StorageUtils
import com.xieli.invitesdk.utils.StringUtils
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.TreeMap
import java.util.concurrent.TimeUnit
/**
 * @Auther sr
 * @Date 2023/9
 * @Description 构建网络请求模块
 */
object OkhttpModule {


    //拼接链接
    var INVITE_H5_URL =
        if (StorageUtils.isdebug) "http://guoqiang.alitest.yiyongcad.com/" else "http://h5.daotudashi.com/"

    //邀请有礼请求url
    var BASE_URL =
        if (StorageUtils.isdebug) "http://115.159.44.133:8992/" else "https://app.xunjiepdf.com/"


    /**
     * 获取retrofit对象
     */
    fun retrofit(url: String): Retrofit {
        return Retrofit.Builder()
            .client(mOkHttpClient())
            .baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    /**
     * 设置请求丶日志拦截器
     */
    fun mOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient.Builder()
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        builder.addInterceptor(httpLoggingInterceptor)
        builder
            .addInterceptor(InviteInterceptor())
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
        return builder.build()
    }
}

/**
 * 邀请有礼请求拦截器,公共参数
 */
class InviteInterceptor : Interceptor {
    private val mGson: Gson by lazy {
        GsonBuilder().disableHtmlEscaping().create()
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        if (request.body is FormBody) {
            val body = request.body as FormBody?
            val params = TreeMap<String, Any>()
            body?.let {
                for (i in 0 until it.size) {
                    params[it.name(i)] = it.value(i)
                }
            }

            params.takeIf {
                params.containsKey("none")
            }?.remove("none")


            if (!params.containsKey("timestamp")) {
                params["timestamp"] = (System.currentTimeMillis()) / 1000
            }
            params["deviceid"] = StorageUtils.deviceid
            params["productinfo"] = StorageUtils.productinfo

            val paramsKet = params.keys
            val jsonBuild = StringBuilder()
            for (key in paramsKet) {
                jsonBuild.append("&").append(key).append("=").append(params[key])
            }
            jsonBuild.deleteCharAt(0)
            jsonBuild.append("hUuPd20171206LuOnD")
            var datasign = StringUtils.Md5(jsonBuild.toString())
            params["datasign"] = datasign

            val json = mGson.toJson(params)
            Log.i("okhttp", "\n请求地址: ${request.url}\n请求参数:${json}")
            request = request.newBuilder()
                .post(json.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull()))
                .build()
        }
        return chain.proceed(request)
    }
}